<?php
namespace AliPay;

/**
 *
 * @author lovebing <i@lovebing.org>
 */
class DirectPayWap extends BaseWap {

    private $authApi = 'alipay.wap.trade.create.direct';
    private $tradeApi = 'alipay.wap.auth.authAndExecute';
    private $token = '';

    /**
     * 
     * @param AccountInfo $account
     * @param PayParams $params
     * @throws Exception
     */
    public function __construct(AccountInfo $account, PayParams $params) {
        if (!in_array(gettype($params->totalFee), array('double', 'integer'))) {
            throw new Exception('Param Type Error', -1);
        }
        if ($params->tradeNo == '' || $params->subject == '' || $params->totalFee <= 0) {
            throw new Exception('Param Value Error', -2);
        }
        $this->md5Key = $account->md5Key;
        $this->businessParams = array(
            'subject' => $params->subject ,
            'out_trade_no' => $params->tradeNo,
            'total_fee' => $params->totalFee,
            'seller_account_name' => $account->sellerAccountName,
            'call_back_url' => $params->returnUrl,
            'notify_url' => $params->notifyUrl
        );
        $this->auth();
    }

    private function auth() {
        $this->type = 'auth';
        $this->mainParams['service'] = $this->authApi;
        $this->mainParams['req_id'] = uniqid();
        $url = $this->getRedirectURL();

        $content = $this->curl_get($url);
        $arr = array();
        parse_str($content, $arr);

        if (isset($arr['res_data'])) {
            $data = simplexml_load_string($arr['res_data']);
            $this->token = $data->request_token->__toString();
        }
        else {
            exit('Error:'.print_r($arr, true));
        }
    }

    private function trade() {
        $this->type = 'trade';
        $this->businessParams = array(
            'request_token' => $this->token
        );
        $this->mainParams['service'] = $this->tradeApi;
        $this->mainParams['req_id'] = uniqid();

        return $this->getRedirectURL();
    }

    function curl_get($url, $get = array()) {
        $defaults = array(
            CURLOPT_URL => $url . (strpos($url, '?') === FALSE ? '?' : '') . http_build_query($get),
            CURLOPT_HEADER => 0,
            CURLOPT_RETURNTRANSFER => TRUE,
            CURLOPT_TIMEOUT => 4
        );
        $ch = curl_init();
        curl_setopt_array($ch, $defaults);
        $result = curl_exec($ch);
        
        if($result === false) {
            exit(curl_error($ch));
        }
        curl_close($ch);
        return $result;
    }

    public function go() {
        $url = $this->trade();
        if ($url != '') {
            header('Location: ' . $url);
        }
    }

}

?>
